#include <QtNetwork/QLocalSocket>
#include <QFileInfo>
#include "singleapplication.h"

#define TIME_OUT                (500)    // 500ms

#define ENV_ESYNC_DATA_DIR		"ESYNC_DATA_DIR"
#define OTA_EVENTS_DIR			"misc/ota_events"
#define HMI_PIPE_TYPE			"engine_running"

SingleApplication::SingleApplication(int argc, char **argv)
    : QApplication(argc, argv)
    , w(NULL)
    , _isRunning(false)
    , _localSocket(NULL)
{
	char *esync_data = getenv(ENV_ESYNC_DATA_DIR);
    _pipeName = QByteArray(esync_data) + QByteArray("/") + QByteArray(OTA_EVENTS_DIR);
    if (argc == 2) {
		//hmi_pipe_type = QByteArray("/") + QByteArray(argv[1]);
        //_pipeName.append(hmi_pipe_type);
		;
	}
    _initLocalConnection();
}

bool SingleApplication::isRunning()
{
    return _isRunning;
}

//void SingleApplication::_newLocalConnection()
//{
//    QLocalSocket *socket = _localServer->nextPendingConnection();
//    if (socket) {
//        socket->waitForReadyRead(2 * TIME_OUT);
//        delete socket;
//        _activateWindow();
//    }
//}

void SingleApplication::_initLocalConnection()
{
    _isRunning = false;

	_localSocket = new QLocalSocket(this);
    _localSocket->connectToServer(_pipeName);
    if (_localSocket->waitForConnected(0)) {
        _isRunning = true;
        return;
    }

	//LocalSocketHandleThread *uCli = new LocalSocketHandleThread(*_localSocket);
	//uCli->start();
}

//void SingleApplication::_newLocalServer()
//{
//    _localServer = new QLocalServer(this);
//    connect(_localServer, SIGNAL(newConnection()), this, SLOT(_newLocalConnection()));
//    if (!_localServer->listen(_pipeName)) {
//        if (_localServer->serverError() == QAbstractSocket::AddressInUseError) {
//            QLocalServer::removeServer(_pipeName);
//            _localServer->listen(_pipeName);
//        }
//    }
//}

void SingleApplication::_activateWindow()
{
    if (w) {
        w->showNormal();
        w->activateWindow();
    }
}

//- pipe client -
LocalSocketHandleThread::LocalSocketHandleThread (QLocalSocket &sock)
	: _client(&sock)
{
	connect(_client, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
	connect(_client, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(onError(QLocalSocket::LocalSocketError)));
	connect(_client, SIGNAL(disconnected()), this, SLOT(quit()));
}

LocalSocketHandleThread::~LocalSocketHandleThread()
{
	this->wait();
	this->quit();
}

void LocalSocketHandleThread::run()
{
	while (1) {
		//_client->waitForReadyRead();
		_client->waitForBytesWritten(TIME_OUT);
	}
}

void LocalSocketHandleThread::onReadyRead()
{

}

void LocalSocketHandleThread::onError(QLocalSocket::LocalSocketError err)
{

}

int LocalSocketHandleThread::writeData(QByteArray &data)
{
	return 0;
}
